<template>
  <div class="user-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/home/users' }">用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="mt">
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList" class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="addVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户数据表格 -->
      <el-table :data="userList" class="mt" style="width: 100%" border stript :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
        <!-- 索引列 -->
        <el-table-column label="#" type="index" width="180"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180"> </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"> </el-table-column>
        <el-table-column prop="mobile" label="电话" width="180"> </el-table-column>
        <el-table-column prop="role_name" label="角色" width="180"> </el-table-column>
        <el-table-column label="状态" width="180">
          <!-- {{scope.row}}: 表示的是当前行对应的数据 其实就是数组中的每一个对象 -->
          <!-- template: 自定义布局 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="stateChange(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="操作" width="200">
          <template slot-scope="scope">
            <el-tooltip content="编辑" placement="top" effect="light">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDailog(scope.row.id)"> </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" effect="light">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUserById(scope.row)"> </el-button>
            </el-tooltip>
            <el-tooltip content="分配权限" placement="top" effect="light">
              <el-button type="warning" icon="el-icon-s-tools" size="mini"> </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页导航 -->
      <!-- current-page: 当前页
       page-size: 每页显示多少条 -->
      <el-pagination
        class="mt"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加用户弹窗 -->
      <el-dialog title="添加用户" :visible.sync="addVisible" @close="addDialogClose" width="40%">
        <el-form :model="addUserForm" :rules="addUserRules" ref="addUserRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑用户的弹窗 -->
      <el-dialog title="编辑用户" :visible.sync="editVisible" @close="editDialogClose" width="40%">
        <el-form :model="editUserForm" :rules="editUserRules" ref="editUserRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editUserForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserById">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'users',
  data() {
    // 自定义邮箱的校验规则
    var emailCheck = (rule, val, callback) => {
      // 邮箱的正则
      let emailReg = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/
      if (!emailReg.test(val)) {
        return callback(new Error('邮箱格式错误'))
      }
      // 验证通过
      callback()
    }
    // 自定义手机的校验规则
    var phoneCheck = (rule, val, callback) => {
      // 手机的正则
      let phoneReg = /^(13[0-9]|[01456879]|15 [0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (!phoneReg.test(val)) {
        return callback(new Error('手机号格式错误'))
      }
      // 验证通过
      callback()
    }
    return {
      // 获取用户信息必须携带的数据
      queryInfo: {
        // 搜索相关
        query: '',
        // 当前页码
        pagenum: 1,
        // 每页显示条数
        pagesize: 5,
      },
      // 保存用户信息
      userList: [],
      // 保存总条数
      total: 0,
      // 控制添加用户弹框显示隐藏
      addVisible: false,
      // 添加用户的表单数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 添加用户的表单校验规则
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          // min: 最少3位 max: 最多5位
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // 使用自定义校验规则
          { validator: emailCheck, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '手机号长度必须为11位', trigger: 'blur' },
          { validator: phoneCheck, trigger: 'blur' },
        ],
      },
      // 控制编辑用户弹框显示隐藏
      editVisible: false,
      // 编辑用户的表单数据
      editUserForm: {
        username: '',
        email: '',
        mobile: '',
      },
      // 编辑用户的表单校验规则
      editUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          // min: 最少3位 max: 最多5位
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // 使用自定义校验规则
          { validator: emailCheck, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '手机号长度必须为11位', trigger: 'blur' },
          { validator: phoneCheck, trigger: 'blur' },
        ],
      },
      // 存储编辑用户的id
      editId: '',
    }
  },
  methods: {
    // 获取用户数据
    async getUserList() {
      // 通过get方式往服务端提交数据 需要使用params
      const { data } = await this.$http('users', {
        params: {
          ...this.queryInfo,
        },
      })
      // 保存总条数
      this.total = data.data.total
      if (data.meta.status != 200) return this.$message.info('用户列表获取失败 请稍后重试')
      // 保存数据渲染
      this.userList = data.data.users
    },
    // switch按钮状态改变触发的回调
    async stateChange(row) {
      const { data } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
      if (data.meta.status != 200) {
        // 回到上一次的状态 => 取反
        row.mg_state = !row.mg_state
        return this.$message.info('设置状态失败 ~')
      }
      this.$message.success('设置状态成功 ~')
    },
    // 添加用户的方法
    addUser() {
      this.$refs.addUserRef.validate(async (flag) => {
        if (!flag) return this.$message.error('看不见提示吗兄弟?')
        // 代码能执行到这 证明用户的输入没有问题 此时可以发起请求
        const { data } = await this.$http.post('users', this.addUserForm)
        if (data.meta.status != 201) return this.$message.error('添加用户失败')
        // 刷新页面
        this.getUserList()
        // 隐藏添加用户弹框
        this.addVisible = false
      })
    },
    // 关闭dailog弹框触发的回调
    addDialogClose() {
      // 重置校验规则和表单内容
      this.$refs.addUserRef.resetFields()
    },
    // 当每页条数发生变化时会触发的回调
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 当前页码发生变化时会触发的回调
    handleCurrentChange(newPageNum) {
      this.queryInfo.pagenum = newPageNum
      this.getUserList()
    },
    // 显示编辑框并查询当前用户的数据
    async showEditDailog(id) {
      // 保存id 等会编辑的时候需要使用
      this.editId = id
      const { data } = await this.$http.get(`users/${id}`)
      // 保存当前编辑的用户数据
      this.editUserForm = data.data
      // 显示编辑框
      this.editVisible = true
    },
    // 根据id编辑用户
    async editUserById() {
      await this.$http.put(`users/${this.editId}`, {
        email: this.editUserForm.email,
        mobile: this.editUserForm.mobile,
      })
      // 关闭编辑弹框
      this.editVisible = false
      // 刷新页面 重新获取数据
      this.getUserList()
    },
    // 关闭编辑弹框触发的回调
    editDialogClose() {
      // 重置校验规则和表单内容
      this.$refs.editUserRef.resetFields()
    },
    // 根据id删除用户
    delUserById(row) {
      // 友好提示
      this.$confirm(`此操作将永久删除 ${row.username} 用户, 是否继续?`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data } = await this.$http.delete(`users/${row.id}`)
          if (data.meta.status != 200) return this.$message.error('删除失败 请联系管理员')
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
          // 重新获取数据
          this.getUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },
  created() {
    this.getUserList()
  },
}
</script>
